package com.itheima.service.mongo;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.RecommendVideo;
import com.itheima.domain.mongo.Video;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@Service
public class VideoServiceImpl implements VideoService{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;


    //查询小视频列表
    @Override
    public PageBeanVo findVideo(Long userId, Integer pageNum, Integer pageSize) {

        //查询条件
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("score")))
                .with(Sort.by(Sort.Order.desc("date")))
                .skip((pageNum - 1) * pageSize)
                .limit(pageSize);

        //查询
        List<RecommendVideo> recommendVideoList = mongoTemplate.find(query, RecommendVideo.class);

        //遍历集合，取出小视频id获取视频信息
        List<Video> videoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(recommendVideoList)) {
            for (RecommendVideo recommendVideo : recommendVideoList) {
                Video video = mongoTemplate.findById(recommendVideo.getVideoId(), Video.class);

                videoList.add(video);
            }
        }

        //获取总数
        long count = mongoTemplate.count(query, RecommendVideo.class);

        return new PageBeanVo(pageNum,pageSize,count,videoList);
    }


    //发布小视频
    @Override
    public void saveVideo(Video video) {

        //设置大数据Vid
        video.setVid(idService.getNextId(ConstantUtil.VIDEO_ID));

        //保存
        mongoTemplate.save(video);

        //将小视频推给自己
        RecommendVideo recommendVideo = new RecommendVideo();
        recommendVideo.setDate(System.currentTimeMillis());
        recommendVideo.setScore(100d);
        recommendVideo.setUserId(video.getUserId());
        recommendVideo.setVid(video.getVid());
        recommendVideo.setVideoId(video.getId());

        mongoTemplate.save(recommendVideo);
    }


    //小视频用户关注
    @Override
    public void saveUserFocus(FocusUser focusUser) {
        mongoTemplate.save(focusUser);
    }


    //删除小视频用户关注
    @Override
    public void deleteUserFocus(Long userId, Long videoUserId) {
        Query query = new Query(Criteria.where("userId").is(userId)
                .and("focusUserId").is(videoUserId)
        );

        mongoTemplate.remove(query, FocusUser.class);
    }


    //用户视频
    @Override
    public PageBeanVo findUserVideoList(Long uid, Integer pageNum, Integer pageSize) {

        Query query = new Query(Criteria.where("userId").is(uid))
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((pageNum - 1) * pageSize)
                .limit(pageSize);

        //查询
        List<Video> videoList = mongoTemplate.find(query, Video.class);

        //总数
        long count = mongoTemplate.count(query, Video.class);

        return new PageBeanVo(pageNum, pageSize, count, videoList);
    }



    // 根据id查询
    @Override
    public Video findVideoById(String videoId) {
        return mongoTemplate.findById(new ObjectId(videoId),Video.class );
    }



    @Override
    public PageBeanVo videosCommentsList(String videoId, Integer pageNum, Integer pageSize) {
        //1. 组装查询条件
        Query query = new Query(
                Criteria.where("publishId").is(new ObjectId(videoId))
                        .and("commentType").is(5)
        ).with(Sort.by(Sort.Order.desc("created")))
                .skip((pageNum - 1) * pageSize).limit(pageSize);
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);

        //2. 统计总记录数
        long count = mongoTemplate.count(query, Comment.class);

        //3. 返回封装结果
        return new PageBeanVo(pageNum, pageSize, count, commentList);
    }

    @Override
    public Integer videoCommentsLike(Comment comment,Long userId) {
        //保存子节点comment对象
        Comment commentS = new Comment();
        commentS.setCreated(System.currentTimeMillis());
        commentS.setId(new ObjectId());
        commentS.setPublishUserId(comment.getUserId());
        commentS.setUserId(userId);
        commentS.setCommentType(6);
        commentS.setPublishId(comment.getPublishId());
        mongoTemplate.save(commentS);

        //更新父节点comment对象
        Query query = new Query(Criteria.where("id").is(comment.getId()));
        Update update = new Update();
        update.set("likeCount", comment.getLikeCount() + 1);
        mongoTemplate.updateFirst(query,update,Comment.class);
        return comment.getLikeCount();
    }

    //根据主键查找评论
    @Override
    public Comment findVideoComment(String commentId) {
        Comment comment = mongoTemplate.findById(new ObjectId(commentId), Comment.class);
        return comment;
    }

    @Override
    public Integer videoCommentsDislike(Comment comment, Long userId) {
//        删除子节点comment对象
        Query query1 = new Query(Criteria.where("publishId").is(comment.getPublishId()).
                and("userId").is(userId).and("commentType").is(6));
        mongoTemplate.remove(query1,Comment.class);

        //父节点comment对象count-1
        Query query = new Query(Criteria.where("id").is(comment.getId()));
        Update update = new Update();
        update.set("likeCount", comment.getLikeCount() - 1);
        mongoTemplate.updateFirst(query,update,Comment.class);

        return comment.getLikeCount();
    }
}
